package clientsController;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import model.AnswerObject;
import model.Car;
import model.Fine;
import model.Ipva;
import model.Occurrence;
import databaseController.DatabaseController;

public class Task extends Thread {
	
	private static int _id = 0;
	
	private int identifier;
	private String sensorCode;
	private ObjectOutputStream bufferOut;
	private String message;
	
	public Task(String sensorCode, ObjectOutputStream bufferOut, String message) {
		this.identifier = _id++;
		this.sensorCode = sensorCode;
		this.bufferOut = bufferOut;
		this.message = message;
	}
	
	@Override
	public void run() {
		try {
			ArrayList<Occurrence> occurrence = DatabaseController.getInstance().getOccurrencesDatabase(message, 1);
			DatabaseController.getInstance().addOccurrence(sensorCode, message);
			Car car = DatabaseController.getInstance().getCarByLicensePlate(message);
			
			ArrayList<Fine> fine = DatabaseController.getInstance().getFineByLicensePlate(message);
			ArrayList<Fine> fineNonPayed = new ArrayList<Fine>();
			ArrayList<Fine> finePayed = new ArrayList<Fine>();
			
			for (Fine f : fine) {
				if (f.isPayed()) {
					finePayed.add(f);
				}
				else {
					fineNonPayed.add(f);
				}
			}
			
			ArrayList<Ipva> ipva = DatabaseController.getInstance().getIpvaByLicensePlate(message);
			ArrayList<Ipva> ipvaNonPayed = new ArrayList<Ipva>();
			ArrayList<Ipva> ipvaPayed = new ArrayList<Ipva>();
			
			for (Ipva i : ipva) {
				if (i.isPayed()) {
					ipvaPayed.add(i);
				}
				else {
					ipvaNonPayed.add(i);
				}
			}			
			
			this.bufferOut.writeObject(new AnswerObject(car, fineNonPayed, finePayed, ipvaNonPayed, ipvaPayed, occurrence));
		}
		catch (IOException e) {
			System.err.println("Task:: Couldn't write answer in buffer");
			return;
		}
	}

	public int getIdentifier() {
		return identifier;
	}

	public ObjectOutputStream getBufferOut() {
		return bufferOut;
	}

	public String getMessage() {
		return message;
	}
}
